package com.sayimo.maker.mall.orders.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.sayimo.framework.common.AbstractBaseService;
import com.sayimo.framework.common.util.VerifyCodeUtil;
import com.sayimo.framework.common.util.Date.DateUtil;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.mall.orders.dao.OrdersReceivingAddressInterfaceDao;
import com.sayimo.maker.mall.orders.service.OrdersReceivingAddressInterfaceService;
import com.sayimo.maker.mall.orders.vo.GenerateReceivingAddressResult;
import com.sayimo.maker.mall.orders.vo.OrdersReceivingAddress;
import com.sayimo.maker.user.service.ReceivingAddressInterfaceService;
import com.sayimo.maker.user.vo.ReceivingAddress;

@Service(value = "ordersReceivingAddressInterfaceService")
public class OrdersReceivingAddressInterfaceImplService extends AbstractBaseService implements OrdersReceivingAddressInterfaceService {

	private static Log logger = LogFactory.getLog(OrdersReceivingAddressInterfaceImplService.class);

	@Resource(name = "ordersReceivingAddressInterfaceDao")
	private OrdersReceivingAddressInterfaceDao ordersReceivingAddressInterfaceDao;

	@Resource(name="receivingAddressInterfaceImplService")
	private ReceivingAddressInterfaceService receivingAddressInterfaceService;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public GenerateReceivingAddressResult insertOrdersReceivingBatchCode(Integer[] ordersIds, Integer customerId) throws ServiceException {
		logger.info("insertOrdersReceivingBatchCode--");
		
		GenerateReceivingAddressResult generateReceivingAddressResult = new GenerateReceivingAddressResult();

		try {
			OrdersReceivingAddress ordersReceivingAddress = queryOrderReceivingCountByOrdersId(ordersIds[0]);
			
			if (ordersReceivingAddress == null) { // 当前订单没有设置收货地址，则拉取会员默认收货地址信息
				// 获取会员默认收货地址
				ReceivingAddress receivingAddress = receivingAddressInterfaceService.selectMemberDefaultAddress(customerId);

				Map<String, Object> pm = new HashMap<String, Object>();
				String batchCode = generateBatchCode();
				pm.put("batchCode",batchCode);
				pm.put("receivingPeople", (receivingAddress == null || StringUtils.isEmpty(receivingAddress.getReceivingPeople())) ? null: receivingAddress.getReceivingPeople());
				pm.put("telePhone", (receivingAddress == null || StringUtils.isEmpty(receivingAddress.getTelephone())) ? null: receivingAddress.getTelephone());
				pm.put("areaCode",(receivingAddress == null || receivingAddress.getAreaCode() == null) ? null : receivingAddress.getAreaCode());
				pm.put("address",(receivingAddress == null || StringUtils.isEmpty(receivingAddress.getAddress())) ? null : (receivingAddress.getAddress()));

				logger.info("receivingAddress = " + JSONUtil.writeValueAsString(receivingAddress));
				// 联系人
				generateReceivingAddressResult.setReceivePeople((receivingAddress == null || StringUtils.isEmpty(receivingAddress.getReceivingPeople())) ? "": receivingAddress.getReceivingPeople());
				// 电话
				generateReceivingAddressResult.setLinkInformation((receivingAddress == null || StringUtils.isEmpty(receivingAddress.getTelephone())) ? "": receivingAddress.getTelephone());
				// 地址
				generateReceivingAddressResult.setReceiveAddress((receivingAddress == null || StringUtils.isEmpty(receivingAddress.getAddress())) ? "" : receivingAddress.getAddress());
				// 地区编码
				generateReceivingAddressResult.setAreaCode((receivingAddress == null || StringUtils.isEmpty(receivingAddress.getAreaCode())) ? "" : receivingAddress.getAreaCode());
				// 订单批次号
				generateReceivingAddressResult.setBatchCode(batchCode);
				
				String address=null;

				if (StringUtils.isNotEmpty(receivingAddress.getPlaceAddress())) { // 详细地址
					generateReceivingAddressResult.setPlaceAddress(new StringBuilder(receivingAddress.getPlaceAddress())
							.append(address==null?"":address)
							.append(receivingAddress.getAddress()).toString());
				}else{
					generateReceivingAddressResult.setPlaceAddress(generateReceivingAddressResult.getReceiveAddress());
				}
				logger.info("generateReceivingAddressResult" + JSONUtil.writeValueAsString(generateReceivingAddressResult));
				
				List list = new ArrayList();
				for (int i = 0; i < ordersIds.length; i++) {
					Map<String, Object> m = new HashMap<>();
					m.putAll(pm);
					m.put("ordersId", ordersIds[i]);
					
					list.add(m);
				}
				ordersReceivingAddressInterfaceDao.batchInsertOrdersRecevingAddr(list);
			} else { // 当前订单设置了收货地址
				generateReceivingAddressResult.setReceivePeople(StringUtils.isEmpty(ordersReceivingAddress.getReceivingPeople()) ? null: ordersReceivingAddress.getReceivingPeople());
				generateReceivingAddressResult.setLinkInformation(StringUtils.isEmpty(ordersReceivingAddress.getTelePhone()) ? null: ordersReceivingAddress.getTelePhone());
				generateReceivingAddressResult.setReceiveAddress(StringUtils.isEmpty(ordersReceivingAddress.getAddress()) ? null: ordersReceivingAddress.getAddress());
				generateReceivingAddressResult.setIsSchool(ordersReceivingAddress.getIsSchool() == null ? null : ordersReceivingAddress.getIsSchool());
				generateReceivingAddressResult.setBatchCode(ordersReceivingAddress.getBatchCode());
				StringBuilder placeAddressBuilder = new StringBuilder();
				if (StringUtils.isNotEmpty(ordersReceivingAddress.getPlaceAddress())) {
					placeAddressBuilder.append(ordersReceivingAddress.getPlaceAddress());
				}
				if (StringUtils.isNotEmpty(ordersReceivingAddress.getAddress())) {
					placeAddressBuilder.append(ordersReceivingAddress.getAddress());
				}
				
				generateReceivingAddressResult.setPlaceAddress(placeAddressBuilder.toString());
				return generateReceivingAddressResult;
			}
			
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
		return generateReceivingAddressResult;
	}

	public String generateBatchCode() throws ServiceException {
		StringBuffer batchCode = new StringBuffer();
		char[] charArray = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
				'Y', 'Z' };
		Random random = new Random();
		String beforeTwoPlace = String.valueOf(charArray[random.nextInt(26)]) + String.valueOf(charArray[random.nextInt(26)]);
		Date nowDate = new Date();
		batchCode.append(beforeTwoPlace + String.valueOf(DateUtil.getYear(nowDate))
				+ String.valueOf(DateUtil.getMonth(nowDate) < 10 ? "0" + DateUtil.getMonth(nowDate) : DateUtil.getMonth(nowDate))
				+ String.valueOf(DateUtil.getDay(nowDate) < 10 ? "0" + DateUtil.getDay(nowDate) : DateUtil.getDay(nowDate))
				+ VerifyCodeUtil.getNumberVerifyCode(6));
		Integer count = queryOrdersReceivingCountByBatchCode(batchCode.toString());
		if (count > 0) {
			logger.info("batchCode==" + batchCode + "重复，需重新生成");
			generateBatchCode();
		}
		return batchCode.toString();
	}

	@Override
	public Integer queryOrdersReceivingCountByBatchCode(String batchCode) throws ServiceException {
		Integer total = 0;
		try {
			total = ordersReceivingAddressInterfaceDao.queryOrdersReceivingCountByBatchCode(batchCode);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		return total;
	}

	/**
	 * 
	 * @MethodName queryOrdersReceivingAddressByBatchCode
	 * @Description 根据收货地址
	 * 
	 * @author chenpy
	 * @date 2016年1月8日 下午2:39:57
	 * @param
	 * @return List<OrdersReceivingAddress>
	 * @VERSION 1.0.0
	 */
	public List<OrdersReceivingAddress> queryOrdersReceivingAddressByBatchCode(String batchCode) throws ServiceException {
		try {
			return this.ordersReceivingAddressInterfaceDao.queryOrdersReceivingAddressByBatchCode(batchCode);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	@Override
	public OrdersReceivingAddress queryOrderReceivingCountByOrdersId(Integer ordersId) throws ServiceException {
		try {
			return this.ordersReceivingAddressInterfaceDao.queryOrderReceivingCountByOrdersId(ordersId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @MethodName batchUpdateOrderRecevingAddr
	 * @Description 批量修改订单收货地址
	 * 
	 * @author chenpy
	 * @date 2016年1月13日 下午5:06:02
	 * @param
	 * @return Integer
	 * @VERSION 1.0.0
	 */
	public Integer batchUpdateOrderRecevingAddr(List<OrdersReceivingAddress> list) throws ServiceException {
		try {
			return this.ordersReceivingAddressInterfaceDao.batchUpdateOrderRecevingAddr(list);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	@Override
	public List<OrdersReceivingAddress> queryOrderReceivingCountByOrdersIds(List<Integer> ids) throws ServiceException {
		try{
			return this.ordersReceivingAddressInterfaceDao.queryOrderReceivingCountByOrdersIds(ids);
		}catch(DaoException de){
			logger.error(de);
			throw new ServiceException(de);
		}
		
	}

	/** 
	  * @package com.sayimo.school.mall.service.ope.impl
	  * @author chenpy
	  * @Title:  insertOrdersReceivingAddress
	  * @Description: 新增订单收货地址
	  * @param 
	  * @throws 
	  * @return int
	  * @date 2016年6月17日
	  */
	@Override
	public int insertOrdersReceivingAddress(Map<String, Object> paramAddress)
			throws ServiceException {
		try {
			return ordersReceivingAddressInterfaceDao.insertOrdersReceivingAddress(paramAddress);
		} catch (DaoException e) {
			logger.debug(e);
			throw new ServiceException(e);
		}
	}

}
